#ifndef _LIST_H
#define _LIST_H

//#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
//#define container_of(ptr, type, member) ({          \
//    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
//    (type *)( (char *)__mptr - offsetof(type,member) );})

#define offset_of(type, member)             (unsigned long) &((type*)0)->member
#define container_of(ptr, type, member)     ((type *)((char *)(ptr) - offset_of(type, member)))

typedef struct list_structure
{
    struct list_structure* next;
    struct list_structure* prev;
} list_obj_t;

#define LIST_HEAD_INIT(name)    {&(name), &(name)}
#define LIST_HEAD(name)         list_obj_t name = LIST_HEAD_INIT(name)

inline void list_init(list_obj_t *list)
{
    list->next = list;
    list->prev = list;
}

void list_insert(list_obj_t* list, list_obj_t* node);
void list_insert_tail(list_obj_t* list, list_obj_t* node);
void list_remove(list_obj_t* node);
int list_isempty(const list_obj_t* list);
unsigned int list_len(const list_obj_t* list);

#define list_entry(node, type, member) \
    container_of(node, type, member)

#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

#define list_for_each_safe(pos, n, head) \
  for (pos = (head)->next, n = pos->next; pos != (head); \
    pos = n, n = pos->next)

#endif
